import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class ZtParkTitle extends StatefulWidget {
  late Widget child;
  final Function clickCallback;
  late bool disable;
  ZtParkTitle(
      {super.key,
      required this.child,
      required this.clickCallback,
      required this.disable});

  @override
  State<ZtParkTitle> createState() => _ZtParkTitleState();
}

class _ZtParkTitleState extends State<ZtParkTitle> {
  late final ZtParkTitleController controller;
  String randomId = '${Random().nextInt(1000)}';
  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    controller =
        Get.put<ZtParkTitleController>(ZtParkTitleController(), tag: randomId);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (!widget.disable) {
          controller.startJumpAnimation();
        }
      },
      child: Obx(() {
        return AnimatedContainer(
          onEnd: () {
            widget.clickCallback();
          },
          duration: const Duration(milliseconds: 400),
          transform:
              Matrix4.translationValues(0, -controller.animationValue.value, 0),
          child: widget.child,
        );
      }),
    );
  }
}

class ZtParkTitleController extends GetxController
    with SingleGetTickerProviderMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  final animationValue = RxDouble(0.0);
  final maxJumps = 2.obs;
  var currentJumps = 0.obs;
  final originalValue = 0.0;

  @override
  void onInit() {
    super.onInit();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );

    _animation = Tween<double>(begin: 0, end: 30).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0, 1, curve: Curves.easeInOut),
      ),
    )..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          currentJumps.value++;
          if (currentJumps.value >= maxJumps.value) {
            _controller.reverse();
          } else {
            _controller.forward(from: 0);
          }
        } else if (status == AnimationStatus.dismissed) {
          if (currentJumps.value >= maxJumps.value) {
            animationValue.value = originalValue;
          }
        }
      });

    _animation.addListener(() {
      animationValue.value = _animation.value;
    });
  }

  @override
  void onClose() {
    _controller.dispose();
    super.onClose();
  }

  void startJumpAnimation() {
    if (_controller.isAnimating) {
      return;
    }

    currentJumps.value = 0;
    _controller.forward(from: 0);
  }
}
